package com.aaa.limits.service.impl;

import com.aaa.common.util.ConstUtil;
import com.aaa.common.util.OssUtil;
import com.aaa.limits.service.CommonFileHandlerService;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
 * @ fileName:CommonFileHandlerServiceImpl
 * @ description:
 * @ author:lx
 * @ createTime:2023/6/21 20:33
 * @ version:1.0.0
 */
@Service
public class CommonFileHandlerServiceImpl implements CommonFileHandlerService  {
    @Override
    public Map uploadFile(MultipartFile multipartFile, String savePath) {
        InputStream inputStream= null;
        try {
            //根据文件对象获取字节流
            inputStream = multipartFile.getInputStream();
            //获取文件名称
            String originalFilename = multipartFile.getOriginalFilename();
            //根据源文件名称获取后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //拼装新文件名称 UUID.randomUUID().toString() 随机一个字符串  世界上最好的计算机，不停的运行160年，可以获取两个相同的
            String newFileName= UUID.randomUUID().toString()+suffix;
            //拼装新文件的路径
            savePath = savePath+newFileName;
            //调用封装类
            OssUtil.uploadFile(inputStream,savePath);
            //定义返回对象
            Map returnMap = new HashMap();
            //放入原始文件名称
            returnMap.put("fileOrgName",originalFilename);
            returnMap.put("filePath", ConstUtil.FileHandLeConfig.BUCKET_DAEMON+savePath);
            return returnMap;
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return null;
    }
}

